package com.lsh.oms.provider.writer;

import com.lsh.base.common.model.CommonResult;
import com.lsh.base.lang.json.Jsons;
import com.lsh.oms.core.records.core.JsonType;
import com.lsh.oms.core.service.tool.Pageable;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import static java.util.stream.Collectors.toList;

public class PageWriter implements MessageBodyWriter<Pageable> {
    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return Pageable.class.isAssignableFrom(type);
    }

    @Override
    public long getSize(Pageable page, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return 0;
    }

    @Override
    public void writeTo(Pageable page, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {

        Map<String, Object> pageJson = new HashMap<>();
        pageJson.put("page", page.getPage());
        pageJson.put("total_count", page.getTotalCount());
        pageJson.put("total_page", page.getTotalPage());
        pageJson.put("entries", page.getEntries().stream().map($ -> ($ instanceof JsonType) ? ((JsonType) $).toJson() : $).collect(toList()));
        try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(entityStream, "UTF-8")) {
            outputStreamWriter.write(Jsons.toJsonString(CommonResult.success(pageJson)));
        }
    }
}
